package com.joke.mydiary.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.joke.mydiary.R;
import com.joke.mydiary.pojo.Diary;
import com.joke.mydiary.utils.BitmapUtils;

import org.w3c.dom.Text;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * A simple {@link Fragment} subclass.
 */
public class AddDiaryFragment extends Fragment implements View.OnClickListener {

    public static final int PHOTO_CODE = 0x99;
    private static final int IMAGE_CODE = 0x100;
    private TextView txtDate;
    private EditText txtContent;
    private Button btnSave, btnImage, btnPhoto;
    private ImageView imageView;
    private AddDiaryFragmentListener mListener;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //拍照
    private File photoFile;
    //选择图片
    private Uri uri;
    private InputStream in;

    public AddDiaryFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (AddDiaryFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_add_diary, container, false);
        txtDate = (TextView) view.findViewById(R.id.txtDate);
        imageView = (ImageView) view.findViewById(R.id.imageView);
        String date = sdf.format(new Date());
        txtDate.setText(date);
        txtContent = (EditText) view.findViewById(R.id.txtContent);
        btnSave = (Button) view.findViewById(R.id.btnSave);
        btnImage = (Button) view.findViewById(R.id.btnImage);
        btnPhoto = (Button) view.findViewById(R.id.btnPhoto);
        btnSave.setOnClickListener(this);
        btnImage.setOnClickListener(this);
        btnPhoto.setOnClickListener(this);
        return view;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnSave:
                boolean flag = mListener.saveDiary(saveDiary());
                if (flag) {
                    Toast.makeText((Context) mListener, "保存成功！", Toast.LENGTH_SHORT).show();
                    mListener.showListDiaryFramgment();
                }
                break;
            case R.id.btnImage:
                chooseImage();
                break;
            case R.id.btnPhoto:
                takePhoto();
                break;
        }

    }

    //用于封装Diary对象
    public Diary saveDiary() {
        if (TextUtils.isEmpty(txtContent.getText())) {
            Toast.makeText((Context) mListener, "请输入内容！", Toast.LENGTH_SHORT).show();
            return null;
        }
        Diary diary;
        try {
            diary = new Diary();
            diary.setDate(sdf.parse(txtDate.getText().toString()));
            diary.setContent(txtContent.getText().toString());
            if (photoFile != null) {
                diary.setImagePath(photoFile.getPath());
            } else if (uri != null) {
                diary.setImagePath(uri.toString());
            }
            return diary;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    //启动系统相机
    public void takePhoto() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getOutputMediaFileUri());
        startActivityForResult(intent, PHOTO_CODE);
    }

    //选择图片
    public void chooseImage() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == PHOTO_CODE) {
                Bitmap bm = BitmapUtils.decodeSimpledBitmapFromResourse(photoFile.getPath(),400,400);
                imageView.setImageBitmap(bm);
                imageView.setAdjustViewBounds(true);
            } else if (requestCode == IMAGE_CODE) {
                uri = data.getData();
                in = mListener.getUriInput(uri);
                if (in != null) {
                    photoFile=getOutputMediaFile(in);
                    Bitmap bm = BitmapUtils.decodeSimpledBitmapFromResourse(photoFile.getPath(), 400, 400);
                    imageView.setImageBitmap(bm);
                    imageView.setAdjustViewBounds(true);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //取得拍照完毕的照片的uri
    private Uri getOutputMediaFileUri() {
        photoFile = getOutputMeidaFile();
        return Uri.fromFile(photoFile);
    }

    //用于拍照完毕后保存文件
    private File getOutputMeidaFile() {
        String fileName = System.currentTimeMillis() + ".jpg";
        String rootPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
        File rootFile=new File(rootPath);
        if(!rootFile.exists())
        {
            rootFile.mkdirs();
        }

        File mediaFile = new File(rootPath + File.separator + fileName);


        return mediaFile;
    }
    //用户选择图片后通过InputStream备份一个图片
    public File getOutputMediaFile(InputStream in) {
        String fileName = System.currentTimeMillis() + ".jpg";
        String rootPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
        File rootFile=new File(rootPath);
        if(!rootFile.exists())
        {
            rootFile.mkdirs();
        }

        File mediaFile = new File(rootPath + File.separator + fileName);

        int len = 0;
        byte[] buf = new byte[1024];
        BufferedOutputStream bufOut;
        try {
            bufOut = new BufferedOutputStream(new FileOutputStream(mediaFile));
            while ((len = in.read(buf)) != -1) {
                bufOut.write(buf, 0, len);
                bufOut.flush();
            }
            bufOut.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaFile;
    }


    /**
     * 回调接口
     */
    public interface AddDiaryFragmentListener {
        public boolean saveDiary(Diary diary);

        public void showListDiaryFramgment();

        public InputStream getUriInput(Uri uri);
    }


}
